<?php

/**
 * enquete actions.
 *
 * @package    Terapia Vital
 * @subpackage enquete
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class enqueteActions extends sfActionsFoxsis
{
	public function executeIndex(sfWebRequest $request)
	{
		return $this->forward('enquete', 'list');
	}

	public function executeGrid()
	{
		//Recupero todas as informações necessárias para trabalhar com o grid
		$this->getRequestDataTable();
		$this->data					= EnqueteTable::consultar($this->filter, $this->order);
		$this->total_data			= count($this->data);
		$this->data					= $this->paginadorDataTable($this->data, $this->page_num, parent::LIMIT_PAGE_DATA_TABLE);

		sfLoader::loadHelpers(array('Url'));

	    foreach($this->data as $key => &$r)
	    {
	    	$r['st_enquete'] = ($r['st_enquete'] == "S")? 'SIM' : 'NÃO';
	    	$actions = array(
				'edit'	 => "<a href='".url_for($this->getModuleName().'/edit?id_enquete='.$r['id_enquete'])."' class='icoEditar'></a>",
				'delete' => "<a href='".url_for($this->getModuleName().'/delete?id_enquete='.$r['id_enquete'])."'  class='icoExcluir delete'></a>",
			);
			$this->data[$key]['act'] = implode(' ', $actions);
    	}

		$this->setJSONDataTable($this->data, $this->colunas, $this->total_data);
		return sfView::NONE;
	}


    public function executeList()
    {
        $this->form = new EnqueteForm();
    	$this->colunas	= array(
    		$this->form['id_enquete']->renderLabel() => "id_enquete",
			$this->form['ds_pergunta']->renderLabel() => "ds_pergunta",
			$this->form['st_enquete']->renderLabel() => "st_enquete",
			"Ações"	=> "act"
		);

        $this->filter = $this->_getFilter();
        $this->setTemplate('index');
    }

    public function executeFilter()
	{
	    $filter = new Filtro(
			$this->getRequestParameter(sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());

		$this->getUser()->setAttribute(
			sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE,
			serialize($filter),
			$this->getModuleName()
		);

		return $this->forward($this->getModuleName(), '/list');
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->form = new EnqueteForm();
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$this->form = new EnqueteForm();

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'new');
	}

	public function validateCreate()
	{
		return true;
	}

	public function handleErrorCreate()
	{
		return $this->forward($this->getModuleName(), 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($enquete = Doctrine::getTable('Enquete')->find(array($request->getParameter('id_enquete'))), sprintf('Object enquete does not exist (%s).', $request->getParameter('id_enquete')));
		$this->form = new EnqueteForm($enquete);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($enquete = Doctrine::getTable('Enquete')->find(array($request->getParameter('id_enquete'))), sprintf('Object enquete does not exist (%s).', $request->getParameter('id_enquete')));
		$this->form = new EnqueteForm($enquete);

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'edit');
	}

	public function validateUpdate()
	{
		return true;
	}

	public function handleErrorUpdate()
	{
		return $this->forward($this->getModuleName(), 'edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();

			$this->forward404Unless($enquete = Doctrine::getTable('Enquete')->find(array($request->getParameter('id_enquete'))), sprintf('Object enquete does not exist (%s).', $request->getParameter('id_enquete')));
			$enquete->delete();

			$this->redirect('enquete/index');
		}
		catch(Excepiton $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('enquete/index');
		}
  	}

  	protected function processForm(sfWebRequest $request, sfForm $form)
  	{
  		try
  		{
  			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
  			if ($form->isValid())
  			{
		    	$enquete = $form->save();
		    	
		    	$this->saveOpcao($enquete, $request->getParameter('enquete_opcao'));
		    	
		      	$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.');
		      	$this->redirect('enquete/edit?id_enquete='.$enquete->getIdEnquete());
  			}
  			else
  			{
  				throw new Exception($form->getErrorSchema());
  			}
	    }
	    catch(Exception $e)
	    {
	    	$this->getUser()->setFlash('erro', $e->getMessage());
	    }
  	}
  	
  	public function saveOpcao(Enquete $enquete, array $opcoes)
  	{
  		// retiro os novos do array passado.
  		if(array_key_exists('new', $opcoes))
  			$new = array_pop($opcoes);
  		
  		// Edito as opçoes
  		foreach ($opcoes as $key => $opcao)
  		{
  			foreach($opcoes[$key] as $k => $v)
  			{
  				$enqueteOpcao = Doctrine::getTable('EnqueteOpcao')->find($k);
  				$enqueteOpcao->setDsOpcao($v);
  				$enqueteOpcao->save();
  			}
  		}
  		
  		// salvo as novas opçoes
  		if(isset($new)){
	  		foreach($new as $o)
	  		{
	  			$enqueteOpcao = new EnqueteOpcao();
	  			$enqueteOpcao->setIdEnquete($enquete->getIdEnquete());
	  			$enqueteOpcao->setDsOpcao($o);
	  			$enqueteOpcao->save();
	  		}
  		}
  	}
}
